<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片转绘 - AI创意转换工具</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        }
        
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .card-shadow {
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }
        
        .glow {
            box-shadow: 0 0 15px rgba(102, 126, 234, 0.5);
        }
        
        .upload-area {
            transition: all 0.3s ease;
        }
        
        .upload-area.dragover {
            border-color: #667eea;
            background-color: rgba(102, 126, 234, 0.05);
        }
        
        .result-image {
            transition: transform 0.3s ease;
        }
        
        .result-image:hover {
            transform: scale(1.02);
        }
        
        .loading-spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
    </style>
</head>
<body class="min-h-screen py-8">
    <div class="container mx-auto px-4 max-w-6xl">
        <!-- 标题区域 -->
        <header class="text-center mb-12">
            <h1 class="text-4xl md:text-5xl font-bold text-gray-800 mb-4">图片转绘工具</h1>
            <p class="text-lg text-gray-600 max-w-2xl mx-auto">使用AI技术将您的图片转绘为不同风格图像，释放创意无限可能</p>
            <div class="w-24 h-1 gradient-bg rounded-full mx-auto mt-6"></div>
        </header>

        <!-- 主要内容区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-12">
            <!-- 上传区域 -->
            <div class="bg-white rounded-2xl card-shadow p-6">
                <h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center">
                    <i class="fas fa-upload text-indigo-500 mr-3"></i>
                    上传图片
                </h2>
                
                <!-- API密钥输入 -->
                <div class="mb-6">
                    <label class="block text-gray-700 font-medium mb-2">API密钥</label>
                    <div class="relative">
                        <input type="password" id="apiKey" placeholder="请输入您的API密钥"
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all">
                        <button id="toggleKey" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-indigo-600 transition-colors">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <p class="text-sm text-gray-500 mt-2">请输入您的bizyair API密钥以使用服务</p>
                </div>

                <!-- 文本提示词输入（默认隐藏） -->
                <div id="promptSection" class="mb-6 hidden">
                    <div class="flex items-center justify-between mb-2">
                        <label class="block text-gray-700 font-medium">文本提示词</label>
                        <button id="togglePrompt" class="text-sm text-indigo-600 hover:text-indigo-800 transition-colors">
                            <i class="fas fa-times mr-1"></i>关闭
                        </button>
                    </div>
                    <textarea id="promptInput" rows="3" placeholder="输入AI图像生成的提示词（可选）"
                              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all resize-none"></textarea>
                    <p class="text-sm text-gray-500 mt-2">输入提示词可以更精确地控制AI生成结果</p>
                </div>

                <!-- 开启提示词按钮 -->
                <div class="mb-4">
                    <button id="enablePrompt" class="px-4 py-2 text-indigo-600 border border-indigo-600 rounded-lg hover:bg-indigo-50 transition-colors">
                        <i class="fas fa-plus mr-2"></i>开启文本提示词
                    </button>
                </div>

                <!-- 上传区域 -->
                <div id="uploadArea" class="upload-area border-2 border-dashed border-gray-300 rounded-xl p-8 text-center cursor-pointer mb-6">
                    <input type="file" id="imageUpload" accept="image/*" class="hidden">
                    <i class="fas fa-cloud-upload-alt text-5xl text-gray-400 mb-4"></i>
                    <p class="text-gray-600 font-medium mb-2">点击或拖拽图片到此处上传</p>
                    <p class="text-gray-500 text-sm">支持 JPG、PNG 格式，最大10MB</p>
                </div>
                
                <!-- 图片预览 -->
                <div id="previewContainer" class="hidden mb-6">
                    <h3 class="text-lg font-medium text-gray-700 mb-3">图片预览</h3>
                    <div class="relative rounded-lg overflow-hidden border border-gray-200">
                        <img id="previewImage" src="" alt="预览图" class="w-full h-auto">
                        <button id="removeImage" class="absolute top-3 right-3 bg-white rounded-full p-2 shadow-md hover:bg-gray-100 transition-colors">
                            <i class="fas fa-times text-red-500"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 生成按钮 -->
                <button id="generateBtn" class="w-full gradient-bg text-white font-semibold py-4 rounded-lg hover:opacity-90 transition-all flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed">
                    <i class="fas fa-magic mr-2"></i>
                    生成手办图片
                </button>
            </div>
            
            <!-- 结果区域 -->
            <div class="bg-white rounded-2xl card-shadow p-6">
                <h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center">
                    <i class="fas fa-cube text-purple-500 mr-3"></i>
                    转换结果
                </h2>
                
                <div id="resultArea" class="border border-gray-200 rounded-xl p-8 text-center bg-gray-50 min-h-[300px] flex flex-col items-center justify-center">
                    <i class="fas fa-image text-5xl text-gray-400 mb-4"></i>
                    <p class="text-gray-500">生成的手办图片将显示在这里</p>
                </div>
                
                <!-- 加载指示器 -->
                <div id="loadingIndicator" class="hidden mt-6">
                    <div class="flex items-center justify-center">
                        <div class="loading-spinner"></div>
                        <p class="ml-4 text-gray-700 font-medium">正在生成图片，请稍候...</p>
                    </div>
                </div>
                
                <!-- 下载按钮 -->
                <div id="downloadSection" class="hidden mt-6">
                    <button id="downloadBtn" class="w-full bg-green-500 text-white font-semibold py-3 rounded-lg hover:bg-green-600 transition-all flex items-center justify-center">
                        <i class="fas fa-download mr-2"></i>
                        下载手办图片
                    </button>
                </div>
            </div>
        </div>
        
        
        
        <!-- 使用说明 -->
        <div class="bg-white rounded-2xl card-shadow p-8 mb-12">
            <h2 class="text-2xl font-bold text-gray-800 mb-6 text-center">使用说明</h2>
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                <div class="text-center">
                    <div class="w-12 h-12 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center mx-auto mb-3">
                        <span class="font-bold">1</span>
                    </div>
                    <h3 class="font-semibold text-gray-800 mb-2">配置环境</h3>
                    <p class="text-gray-600 text-sm">系统会自动从Cookie读取BIZY_KEY，若无可手动输入</p>
                </div>

                <div class="text-center">
                    <div class="w-12 h-12 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center mx-auto mb-3">
                        <span class="font-bold">2</span>
                    </div>
                    <h3 class="font-semibold text-gray-800 mb-2">开启文本提示词（可选）</h3>
                    <p class="text-gray-600 text-sm">点击按钮开启，可输入提示词控制生成效果</p>
                </div>

                <div class="text-center">
                    <div class="w-12 h-12 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center mx-auto mb-3">
                        <span class="font-bold">3</span>
                    </div>
                    <h3 class="font-semibold text-gray-800 mb-2">上传图片</h3>
                    <p class="text-gray-600 text-sm">点击上传区域或拖拽图片文件进行上传</p>
                </div>

                <div class="text-center">
                    <div class="w-12 h-12 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center mx-auto mb-3">
                        <span class="font-bold">4</span>
                    </div>
                    <h3 class="font-semibold text-gray-800 mb-2">生成并下载</h3>
                    <p class="text-gray-600 text-sm">点击生成按钮，完成后下载AI处理结果</p>
                </div>
            </div>

            <!-- API信息说明 -->
            <div class="mt-8 p-4 bg-blue-50 rounded-lg">
                <h3 class="font-semibold text-blue-800 mb-2">
                    <i class="fas fa-info-circle mr-2"></i>API接口说明
                </h3>
                <div class="text-sm text-blue-700 space-y-1">
                    <p>• 页面URL格式：http://localhost:8000/pic.php?login=用户名&api_id=38913</p>
                    <p>• login参数对应Cookie中的enorg值</p>
                    <p>• api_id对应API配置中的不同模板</p>
                    <p>• 系统优先使用Cookie中的BIZY_KEY，其次使用环境变量</p>
                </div>
            </div>
        </div>
        
        <!-- 页脚 -->
        <footer class="text-center text-gray-600">
            <p> </p>
        </footer>
    </div>

    <!-- 图片放大模态框 -->
    <div id="imageModal" class="fixed inset-0 bg-black bg-opacity-80 z-50 hidden items-center justify-center p-4">
        <div class="max-w-4xl max-h-full">
            <button id="closeModal" class="absolute top-4 right-4 text-white text-2xl hover:text-gray-300 transition-colors">
                <i class="fas fa-times"></i>
            </button>
            <img id="modalImage" src="" alt="放大图片" class="max-w-full max-h-full object-contain">
        </div>
    </div>

    <script>
        // DOM元素
        const uploadArea = document.getElementById('uploadArea');
        const imageUpload = document.getElementById('imageUpload');
        const previewContainer = document.getElementById('previewContainer');
        const previewImage = document.getElementById('previewImage');
        const removeImage = document.getElementById('removeImage');
        const generateBtn = document.getElementById('generateBtn');
        const resultArea = document.getElementById('resultArea');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const apiKeyInput = document.getElementById('apiKey');
        const toggleKeyBtn = document.getElementById('toggleKey');
        const downloadSection = document.getElementById('downloadSection');
        const downloadBtn = document.getElementById('downloadBtn');
        const imageModal = document.getElementById('imageModal');
        const modalImage = document.getElementById('modalImage');
        const closeModal = document.getElementById('closeModal');
        const promptSection = document.getElementById('promptSection');
        const enablePromptBtn = document.getElementById('enablePrompt');
        const togglePromptBtn = document.getElementById('togglePrompt');
        const promptInput = document.getElementById('promptInput');

        // 变量
        let uploadedImage = null;
        let imageFile = null;
        let generatedImageUrl = null;

        // 切换API密钥显示/隐藏
        toggleKeyBtn.addEventListener('click', () => {
            const type = apiKeyInput.getAttribute('type') === 'password' ? 'text' : 'password';
            apiKeyInput.setAttribute('type', type);
            toggleKeyBtn.innerHTML = type === 'password'
                ? '<i class="fas fa-eye"></i>'
                : '<i class="fas fa-eye-slash"></i>';
        });

        // 开启文本提示词
        enablePromptBtn.addEventListener('click', () => {
            promptSection.classList.remove('hidden');
            enablePromptBtn.classList.add('hidden');
            promptInput.focus();
        });

        // 关闭文本提示词
        togglePromptBtn.addEventListener('click', () => {
            promptSection.classList.add('hidden');
            enablePromptBtn.classList.remove('hidden');
            promptInput.value = '';
        });

        // 上传区域点击触发文件选择
        uploadArea.addEventListener('click', () => {
            imageUpload.click();
        });

        // 拖拽功能
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            if (e.dataTransfer.files && e.dataTransfer.files[0]) {
                handleImageUpload(e.dataTransfer.files[0]);
            }
        });

        // 处理文件选择
        imageUpload.addEventListener('change', (e) => {
            if (e.target.files && e.target.files[0]) {
                handleImageUpload(e.target.files[0]);
            }
        });

        // 处理图片上传
        function handleImageUpload(file) {
            // 检查文件类型
            if (!file.type.match('image.*')) {
                alert('请上传图片文件（JPG、PNG等格式）');
                return;
            }

            // 检查文件大小 (限制10MB以内)
            if (file.size > 10 * 1024 * 1024) {
                alert('图片大小不能超过10MB');
                return;
            }

            // 存储文件对象
            imageFile = file;
            
            // 读取图片用于预览
            const reader = new FileReader();
            reader.onload = (e) => {
                // 存储预览URL
                uploadedImage = e.target.result;
                previewImage.src = uploadedImage;
                
                // 显示预览
                previewContainer.classList.remove('hidden');
                previewContainer.classList.add('fade-in');
                
                // 添加成功效果
                uploadArea.classList.add('border-green-400', 'bg-green-50');
                setTimeout(() => {
                    uploadArea.classList.remove('border-green-400', 'bg-green-50');
                }, 1000);
            };
            reader.readAsDataURL(file);
        }

        // 移除图片
        removeImage.addEventListener('click', () => {
            uploadedImage = null;
            imageFile = null;
            previewImage.src = '';
            previewContainer.classList.add('hidden');
            imageUpload.value = '';
        });

        // 生成图片
        generateBtn.addEventListener('click', async () => {
            // 获取当前页面的URL参数
            const urlParams = new URLSearchParams(window.location.search);
            const login = urlParams.get('login') || '';
            const api_id = urlParams.get('api_id') || '38913';

            // 验证是否上传了图片
            if (!imageFile) {
                alert('请先上传图片');
                return;
            }

            // 显示加载状态
            generateBtn.disabled = true;
            generateBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>生成中...';
            loadingIndicator.classList.remove('hidden');
            resultArea.innerHTML = '';
            downloadSection.classList.add('hidden');

            try {
                // 第一步：将图片转换为Base64
                const imageBase64 = await fileToBase64(imageFile);

                // 第二步：调用真实的API
                const response = await callRealApi(imageBase64, api_id, login);

                console.log('API响应:', response);

                // 检查API响应是否成功并包含结果图片
                if (response.success && response.api_response && response.api_response.outputs && response.api_response.outputs[0]) {
                    const generatedImageUrl = response.api_response.outputs[0].object_url;

                    // 显示生成的图片
                    resultArea.innerHTML = `
                        <div class="w-full">
                            <h3 class="text-lg font-semibold text-gray-800 mb-4">AI图像生成结果</h3>
                            <div class="relative rounded-lg overflow-hidden result-image">
                                <img src="${generatedImageUrl}" alt="生成图片" class="w-full h-auto rounded-lg cursor-pointer">
                                <div class="absolute bottom-3 right-3 bg-black bg-opacity-60 text-white text-sm px-3 py-1 rounded-full flex items-center">
                                    <i class="fas fa-magic mr-1"></i>AI生成
                                </div>
                            </div>
                            <p class="text-gray-600 text-sm mt-3">点击图片可查看大图</p>

                            <!-- 显示API返回信息 -->
                            <div class="mt-4 p-3 bg-gray-100 rounded-lg">
                                <div class="text-sm text-gray-700">
                                    <p><strong>请求ID:</strong> ${response.api_response.request_id || '无'}</p>
                                    <p><strong>生成数量:</strong> ${response.api_response.outputs.length} 张</p>
                                    <p><strong>生成时间:</strong> ${response.api_response.cost_times?.total_cost_time ? (response.api_response.cost_times.total_cost_time / 1000).toFixed(1) + 's' : '未知'}</p>
                                </div>
                            </div>
                        </div>
                    `;

                    // 添加点击放大事件
                    resultArea.querySelector('img').addEventListener('click', () => {
                        modalImage.src = generatedImageUrl;
                        imageModal.classList.remove('hidden');
                        document.body.style.overflow = 'hidden';
                    });

                    // 添加成功动画
                    resultArea.classList.add('fade-in');

                    // 显示下载按钮，为每个图片生成下载链接
                    const downloadButtons = response.api_response.outputs.map((output, index) => {
                        const imageUrl = output.object_url;
                        const downloadLink = document.createElement('a');
                        downloadLink.href = imageUrl;
                        downloadLink.download = `ai_generated_${response.api_response.request_id}_${index + 1}.png`;
                        downloadLink.className = 'block w-full text-center px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors mb-2';
                        downloadLink.innerHTML = `<i class="fas fa-download mr-2"></i>下载图片 ${index + 1}`;
                        return downloadLink;
                    });

                    downloadSection.innerHTML = '';
                    downloadButtons.forEach(btn => downloadSection.appendChild(btn));
                    downloadSection.classList.remove('hidden');
                    downloadSection.classList.add('fade-in');

                } else {
                    throw new Error(response.message || '生成图片失败，请重试');
                }
            } catch (error) {
                console.error('生成失败:', error);
                resultArea.innerHTML = `
                    <div class="text-center">
                        <i class="fas fa-exclamation-triangle text-amber-500 text-5xl mb-4"></i>
                        <h3 class="text-lg font-semibold text-gray-800 mb-2">生成失败</h3>
                        <p class="text-gray-600 mb-4">${error.message}</p>
                        <p class="text-sm text-gray-500 mb-4">请检查API密钥是否正确，或联系技术支持</p>
                        <button id="retryBtn" class="px-4 py-2 bg-indigo-500 text-white rounded-lg hover:bg-indigo-600 transition-colors">
                            <i class="fas fa-redo mr-1"></i>重试
                        </button>
                    </div>
                `;
                document.getElementById('retryBtn').addEventListener('click', () => {
                    generateBtn.click();
                });
            } finally {
                // 隐藏加载状态
                loadingIndicator.classList.add('hidden');
                generateBtn.disabled = false;
                generateBtn.innerHTML = '<i class="fas fa-magic mr-2"></i>生成图片';
            }
        });

        // 将文件转换为Base64
        function fileToBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => {
                    // 提取Base64部分（去除data:image/xxx;base64,前缀）
                    const base64 = reader.result.split(',')[1];
                    resolve(base64);
                };
                reader.onerror = error => reject(error);
            });
        }

        // 调用真实的API
        async function callRealApi(imageBase64, api_id, login) {
            try {
                // 首先尝试从Cookie获取BIZY_KEY
                const apiKey = getApiKeyFromCookieOrEnv();

                if (!apiKey) {
                    return {
                        success: false,
                        message: '未配置API密钥，请在Cookie中设置BIZY_KEY或配置环境变量'
                    };
                }

                // 准备API请求数据
                const apiData = {
                    web_app_id: parseInt(api_id),
                    suppress_preview_output: true,
                    input_values: {
                        "31:LoadImage.image": `data:image/jpeg;base64,${imageBase64}`
                    }
                };

                // 如果有提示词，添加到请求中
                const prompt = promptInput.value.trim();
                if (prompt) {
                    apiData.input_values["11:TextEncodeQwenImageEditPlus.prompt"] = prompt;
                }

                // 调用API
                const response = await fetch('api.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'login': login,
                        'api_id': api_id
                    },
                    body: JSON.stringify({
                        prompt: prompt || '',
                        image: `data:image/jpeg;base64,${imageBase64}`,
                        batch_size: 1,
                        resolution: '768*1280'
                    })
                });

                const result = await response.json();

                if (result.success) {
                    return {
                        success: true,
                        api_response: result.api_response,
                        message: result.message || '生成成功'
                    };
                } else {
                    return {
                        success: false,
                        message: result.message || 'API调用失败'
                    };
                }
            } catch (error) {
                return {
                    success: false,
                    message: `网络请求失败: ${error.message}`
                };
            }
        }

        // 从Cookie或环境变量获取API密钥
        function getApiKeyFromCookieOrEnv() {
            // 首先尝试从Cookie中获取BIZY_KEY
            const cookieApiKey = getCookie('BIZY_KEY');
            if (cookieApiKey && cookieApiKey.trim()) {
                return cookieApiKey.trim();
            }

            // 如果cookie中没有，尝试从环境变量获取（在浏览器端无法直接访问环境变量）
            // 这里会返回null，实际API获取需要由服务器端处理
            return null;
        }

        // 辅助函数：从Cookie中获取值
        function getCookie(name) {
            const nameEQ = name + "=";
            const ca = document.cookie.split(';');
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i];
                while (c.charAt(0) === ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        // 下载图片
        downloadBtn.addEventListener('click', () => {
            if (!generatedImageUrl) {
                alert('没有可下载的图片');
                return;
            }
            
            // 创建一个临时链接进行下载
            const link = document.createElement('a');
            link.href = generatedImageUrl;
            link.download = '手办风格图片.png';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });

        // 关闭图片模态框
        closeModal.addEventListener('click', () => {
            imageModal.classList.add('hidden');
            document.body.style.overflow = '';
        });

        // 点击模态框背景关闭
        imageModal.addEventListener('click', (e) => {
            if (e.target === imageModal) {
                closeModal.click();
            }
        });

        // 键盘ESC关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && !imageModal.classList.contains('hidden')) {
                closeModal.click();
            }
        });
    </script>
</body>
</html>